package com.itqiqi.api.Transform;

import com.itqiqi.api.pojo.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;


public class TransformTest3_Reduce {

    public static void main(String[] args) throws Exception {

        // 获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        // 使数据有顺序
        env.setParallelism(1);

        DataStreamSource<String> dataStream = env.readTextFile("input/sensor.txt");

        // 转换成SensorReading类型
        SingleOutputStreamOperator<SensorReading> map = dataStream.map((MapFunction<String, SensorReading>) s -> {
            String[] fields = s.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
        });

        // 分组
        KeyedStream<SensorReading, Tuple> keyByMap = map.keyBy("id");

        // 滚动聚合 -- reduce
        SingleOutputStreamOperator<SensorReading> reduce = keyByMap.reduce(new ReduceFunction<SensorReading>() {
            @Override
            public SensorReading reduce(SensorReading sensorReading1, SensorReading sensorReading2) throws Exception {
                return new SensorReading(
                        sensorReading1.getId(),
                        sensorReading2.getTimestamp(),
                        Math.max(sensorReading1.getTemperature(), sensorReading2.getTemperature())
                );
            }
        });

        reduce.print();


        env.execute();

    }
}
